package engine.message;

import java.util.ArrayList;

public class MessageBroadcaster {
	public MessageBroadcaster(Class<?> messageFamily) {
		if(messageFamily == null) {
			throw new NullPointerException();
		}
		MessageFamily = messageFamily;
		_Listeners = new ArrayList<MessageListener_I>();
	}
	public final Class<?> MessageFamily;
	public boolean accepts(Message_A message) {
		if(message == null) {
			return false;
		} else {
			return(MessageFamily.isInstance(message));
		}
	}
	
	public boolean add(MessageListener_I listener) {
		// Do not allow duplicates.
		if(_Listeners.contains(listener)) {
			return false;
		}
		return _Listeners.add((MessageListener_I) listener);
	}
	public boolean remove(MessageListener_I listener) {
		return _Listeners.remove(listener);
	}
	public int broadcast(MessageQueue queue) {
		int messageCount = 0;
		Message_A message = queue.pop();
		while(message != null) {
			messageCount++;
			for(MessageListener_I listener : _Listeners) {
				// If the message was handled, move on to the next message.
				if(listener.handleMessage(message) == true) {
					break; 
				}
			}
			message = queue.pop();
		}
		return messageCount;
	}
	
	public boolean broadcast(Message_A message) {
		for(MessageListener_I listener : _Listeners) {
			if(listener.handleMessage(message) == true) {
				return true; 
			}
		}
		return false;
	}
	
	private ArrayList<MessageListener_I> _Listeners;
}